package com.cjb.base.realm;

import com.cjb.base.domain.Role;
import com.cjb.base.domain.User;
import com.cjb.base.service.RoleService;
import com.cjb.base.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component(value = "platformReaml")
public class PlatformReaml extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.从认证信息中，获取存入的第一个字段的内容
        User user= (User) principalCollection.getPrimaryPrincipal();

        //2.通过当前的用户id值，获取当前用户的角色
        Integer id = user.getId();
        //3.通过用户的id值，获取用户所拥有的角色
        List<Role> list = roleService.getByUid(id);

        //4.创建用户授权的对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (Role role:list) {
            info.addRole(role.getRole_name());
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
      //1.从subject中获取login传入的密码和用户名
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        //2.获取存储的用户名
        String username = token.getUsername();
        //3.通过用户名查询数据库中的用户信息
        User user = userService.getByLoginName(username);
      //4.将用户的信息放入到认证信息中，shiro自动比较subject中的放入的密码和此处传入的密码是否一致
        AuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),getName());

        return info;
    }
}
